import 'dart:async';

import 'package:easy_refresh/easy_refresh.dart';
import 'package:get/get.dart';
import 'package:largefriends/entity/entities/lf_user_entity.dart';
import 'package:largefriends/pages/lf_base_controller.dart';

import '../../../events/change_filter_event.dart';
import '../../../events/user_relation_event.dart';
import '../../../service/manager/lf_event_helper.dart';
import '../../../service/manager/lf_search_filter_helper.dart';
import '../../../net/lf_api_url.dart';

class LfSearchLogic extends LfBaseListController<LfUserEntity> {
  StreamSubscription? filterSubscription, relationSubscription;
  @override
  void onReady() {
    super.onReady();
    filterSubscription =
        LfEventHelper().getEvent().on<ChangeFilterEvent>().listen((event) {
      if (event.action == ChangeFilterAction.search) {
        dataList.clear();
        getCustomParamHttpRequest(isRefresh: true);
      }
    });
    relationSubscription =
        LfEventHelper().getEvent().on<UserRelationEvent>().listen((event) {
      if (dataList.isEmpty) {
        return;
      }
      var entity =
          dataList.firstWhereOrNull((element) => element.userId == event.uid);
      if (entity != null) {
        if (event.type == UserRelationType.block) {
          dataList.remove(entity);
        } else if (event.type == UserRelationType.like) {
          entity.liked = 1;
        } else if (event.type == UserRelationType.unlike) {
          entity.liked = 0;
        } else if (event.type == UserRelationType.wink) {
          entity.winked = 1;
        } else if (event.type == UserRelationType.requestPrivate) {
          entity.privateAlbumStatus = 2;
        }
        update();
        if (dataList.isEmpty) {
          getCustomParamHttpRequest(isRefresh: true);
        }
      }
    });
  }

  @override
  void onClose() {
    filterSubscription?.cancel();
    relationSubscription?.cancel();
    super.onClose();
  }

  @override
  Future<IndicatorResult> getCustomParamHttpRequest({bool isRefresh = false}) {
    return httpRequest(httpUrl: apiSearch, refresh: isRefresh);
  }

  @override
  getCustomRequestParam({bool isRefresh = false}) {
    requestParam.addAll(LfSearchFilterHelper().getSearchFilter().getSearchMap());
    requestParam["find[photo]"] = 1;
    requestParam["offset"] = 20;
    if(isRefresh){
      requestParam["refresh"] = 1;
    }
  }
}
